<template>
  <div>
    <div class="music-player">
      <img
      src="../../../state/返回2.png"
      alt=""
      style="width: 16px; position: fixed; left: 10px; top: 15px"
      @click="navi"
    />
    <div class="album-cover-container">
      <img
        src="../../../state/image.png"
        alt=""
        class="album-cover"
        :class="{ spinning: isPlaying }"
        @click="togglePlay"
      />
    </div>
  <div class="top">
    
    <div class="song-info">
      <h2>{{ songName }}</h2>
      <p>{{ songArtist }}</p>
    </div>
    <div class="progress-bar">
      <input
        type="range"
        min="0"
        max="100"
        value="0"
        class="slider"
        @input="updateProgress"
        @click.stop
      />
      <span class="time">{{ currentTime }} / {{ duration }}</span>
    </div>
    <div class="controls">
      <button class="control-button" @click="prevSong">上一首</button>
      <button class="control-button" @click="togglePlay">
        {{ isPlaying ? "暂停" : "播放" }}
        <!-- <img src="../../../state/zant.svg" alt="" />
        <img src="../../../state/zant.svg" alt="" /> -->
      </button>
      <button class="control-button" @click="nextSong">下一首</button>
    </div>
  </div>
    </div>
    


    <!-- 评论 -->
    <Context />
  </div>
</template>

<script setup>
import axios from "axios";
import { ref, onMounted, watch, onUnmounted } from "vue";
import { useRoute } from "vue-router";
import { useDataStore } from "../../stores/dataStore";
import { useRouter } from "vue-router";
import { eventBus } from "./EventBus.js";
import Context from "./Context.vue";

const dataStore = useDataStore();
const { start, end } = dataStore;
const router = useRouter();

const route = useRoute();
const songName = ref("");
const songArtist = ref("");
const songLink = ref("");
const isPlaying = ref(false);
const duration = ref(0);
const currentTime = ref(0);
const audio = new Audio();

const navi = () => {
  history.back();
};

onMounted(() => {
  player();
});

onUnmounted(() => {
  audio.removeEventListener("timeupdate", updateCurrentTime);
  audio.removeEventListener("loadedmetadata", loadMetadata);
});

const player = async () => {
  songName.value = route.query.value;
  const cid = localStorage.getItem("id");
  try {
    const response = await axios.get(
      `http://localhost:3000/getSongUrl/?name=${songName.value}&id=${cid}`
    );
    songLink.value = response.data.list; // 假设返回的列表中第一个元素是歌曲 URL
  } catch (error) {
    console.error("Error fetching song URL:", error);
  }

  audio.src = songLink.value;
  audio.load();
  audio.addEventListener("timeupdate", updateCurrentTime);
  audio.addEventListener("loadedmetadata", loadMetadata);
};

const togglePlay = () => {
  isPlaying.value = !isPlaying.value;
  if (isPlaying.value) {
    console.log(11);
    Astart();
    localStorage.setItem("isPlaying", songName.value);
    audio.play();
  } else {
    audio.pause();
    Aend();
  }
  eventBus.dispatchEvent(
    new CustomEvent("togglePlay", { detail: { isPlaying: isPlaying.value } })
  );
};

const Astart = () => {
  songName.value = route.query.value;
  const cid = localStorage.getItem("id");
  start(songName.value, cid);
};

const Aend = () => {
  songName.value = route.query.value;
  const cid = localStorage.getItem("id");
  end(songName.value, cid);
};

const updateCurrentTime = () => {
  const newTime = audio.currentTime;
  currentTime.value = formatTime(newTime);
  // 更新进度条的值
  const progress = (newTime / audio.duration) * 100;
  document.querySelector(".slider").value = progress;
};

const loadMetadata = () => {
  duration.value = formatTime(audio.duration);
};

const formatTime = (time) => {
  const minutes = Math.floor(time / 60);
  const seconds = Math.floor(time % 60);
  return `${minutes.toString().padStart(2, "0")}:${seconds
    .toString()
    .padStart(2, "0")}`;
};

const updateProgress = (event) => {
  const progress = event.target.value;
  audio.currentTime = (progress / 100) * audio.duration;
};

const prevSong = () => {
  // 上一首按钮逻辑（待实现）
};

const nextSong = () => {
  // 下一首按钮逻辑（待实现）
};




</script>

<style scoped>
.music-player {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  width: 340px;
  max-width: 100%;
}

.top{
  width: 100%;
}

.album-cover-container {
  width: 150px;
  height: 150px;
  margin-bottom: 20px;
  position: relative;
}

.album-cover {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.spinning {
  animation: spin 5s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.song-info h2 {
  font-size: 18px;
  color: #333;
  margin: 5px 0;
}

.song-info p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.progress-bar {
  width: 100%;
  margin: 20px 0;
}

.slider {
  width: 100%;
  height: 5px;
  background-color: #ddd;
  border-radius: 5px;
  outline: none;
  -webkit-appearance: none;
}

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  background-color: #4caf50;
  cursor: pointer;
}

.time {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.controls {
  display: flex;
  justify-content: space-around;
  width: 100%;
  margin-top: 20px;
}

.control-button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #4caf50;
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.control-button:hover {
  background-color: #45a049;
}

</style>
